package chat.logic;

import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONObject;

/**
 * @time Oct 28, 2009, 19:50:17 PM
 * @author fdcube
 * @version FreeChat-Server v1.1.2
 */
public class Message {

    public static final ArrayList Messages = new ArrayList();
    private static long MsgId = 0;
    private String UserName;
    private String MsgContent;
    private String MsgColor;

    public Message(String UserName, String MsgContent, String MsgColor) {
        this.UserName = UserName;
        this.MsgContent = MsgContent;
        this.MsgColor = MsgColor;
    }

    public String getMsgColor() {
        return MsgColor;
    }

    public void setMsgColor(String MsgColor) {
        this.MsgColor = MsgColor;
    }

    public String getMsgContent() {
        return MsgContent;
    }

    public void setMsgContent(String MsgContent) {
        this.MsgContent = MsgContent;
    }

    public static long getMsgId() {
        return MsgId;
    }

    public static void setMsgId(long MsgId) {
        Message.MsgId = MsgId;
    }

    public String getUserName() {
        return UserName;
    }

    public void setUserName(String UserName) {
        this.UserName = UserName;
    }

 

    public static String getMessages(int MsgCount) {
        if (MsgCount == 0) {
            MsgCount = (int) Message.MsgId;
        }
        if (Message.MsgId - MsgCount <= 0) {
            synchronized (Messages) {
                try {
                    Messages.wait(20011);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Message.class.getName()).log(Level.SEVERE, null, ex);
                    return "2";
                }
            }
            if (Message.MsgId - MsgCount > 0) {
                return new JSONObject(Messages.get(MsgCount)).toString();
            } else {
                return "1";
            }
        } else {
            return new JSONObject(Messages.get(MsgCount)).toString();
        }
    }

    public static Boolean AddMessage(Message MsgIns) {
        if (Messages.size() == 0) {
            Messages.add(MsgIns);
            Message.MsgId = Messages.size();
            synchronized (Messages) {
                Messages.notifyAll();
            }
            return true;
        } else {
            Messages.add(MsgIns);
            Message.MsgId = Messages.size();
            synchronized (Messages) {
                Messages.notifyAll();
            }
            return true;
        }
    }
}
